package mytask.dao;

import java.util.ArrayList;
import java.util.List;
import mytask.model.Project;
import mytask.model.ProjectMember;
import mytask.model.User;
import mytask.model.UserRole;

import org.springframework.stereotype.Repository;

@Repository(value = "projectDAO")
public class ProjectDAOImpl extends GeneralDAO implements ProjectDAO {

	@Override
	public Project getProject(Integer id) {
		return getHibernateTemplate().get(Project.class, id);
	}

	@Override
	public void saveProject(Project project) {
		getHibernateTemplate().saveOrUpdate(project);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Project> listProjects() {
		return getHibernateTemplate().find("from Project");
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Project> listProjects(final User user, final int maxResults) {
		// TODO find a better implementation!
		final List<Project> allProjects = getHibernateTemplate().find(
				"from Project order by timestamp desc");
		final List<Project> myProjects = new ArrayList<Project>();
		for (final Project project : allProjects) {
			for (final ProjectMember member : project.getMembers()) {
				if (member.getUser().getId().equals(user.getId().intValue())) {
					myProjects.add(project);
				}
			}
		}

		return myProjects;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Project> listAcceptedProjects(final User user,
			final int maxResults) {
		// TODO find a better implementation!
		final List<Project> allProjects = getHibernateTemplate().find(
				"from Project order by timestamp desc");
		final List<Project> myProjects = new ArrayList<Project>();
		for (final Project project : allProjects) {
			for (final ProjectMember member : project.getMembers()) {
				if (member.getUser().getId().equals(user.getId().intValue())
						&& member.getRole() != UserRole.REJECTED) {
					myProjects.add(project);
				}
			}
		}

		return myProjects;
	}

}
